package com.circle.interests.biz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.circle.common.core.exception.RRException;
import com.circle.interests.biz.entity.PrizeInfo;
import com.circle.interests.biz.entity.PrizeInventory;
import com.circle.interests.biz.mapper.PrizeInventoryMapper;
import com.circle.interests.biz.service.IPrizeInfoService;
import com.circle.interests.biz.service.IPrizeInventoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 奖品库存 服务实现类
 * </p>
 *
 * @author generator
 * @since 2021-12-05
 */
@Slf4j
@Service
@Transactional
public class PrizeInventoryServiceImpl extends ServiceImpl<PrizeInventoryMapper, PrizeInventory> implements IPrizeInventoryService {

    @Resource
    private IPrizeInfoService prizeInfoService;

    @Override
    public PrizeInventory allocateInventory(Integer sceneType, String sceneId, Long prizeId, Integer type, Integer count) {
        PrizeInventory prizeInventory = new PrizeInventory();
        prizeInventory.setSceneType(sceneType);
        prizeInventory.setSceneId(sceneId);
        prizeInventory.setPrizeId(prizeId);
        prizeInventory.setInventoryType(type);
        prizeInventory.setTotal(count);
        prizeInventory.setRemain(count);
        save(prizeInventory);
        return prizeInventory;
    }

    @Override
    public Integer modifyInventory(Integer sceneType, String sceneId, String prizeCode, Integer count) {
        PrizeInfo prizeInfo = prizeInfoService.getByCode(prizeCode);
        Assert.notNull(prizeInfo, "奖品未找到");
        PrizeInventory prizeInventory = getPrizeInventory(sceneType, sceneId, prizeInfo.getId());
        if (prizeInventory == null) {
            throw new RRException("未找到该库存");
        }
        prizeInventory.setTotal(prizeInventory.getTotal() + count);
        prizeInventory.setRemain(prizeInventory.getRemain() + count);
        updateById(prizeInventory);
        return prizeInventory.getTotal();
    }

    @Override
    public PrizeInventory getPrizeInventory(Integer sceneType, String sceneId, Long prizeId) {
        return getOne(Wrappers.lambdaQuery(PrizeInventory.class)
                .eq(PrizeInventory::getSceneType, sceneType)
                .eq(PrizeInventory::getSceneId, sceneId)
                .eq(PrizeInventory::getPrizeId, prizeId));
    }

    private List<PrizeInventory> listPrizeInventory(Integer sceneType, String sceneId) {
        return list(Wrappers.lambdaQuery(PrizeInventory.class)
                .eq(PrizeInventory::getSceneType, sceneType)
                .eq(PrizeInventory::getSceneId, sceneId));
    }

}
